<template>
  <div class="stepBox">
    <a-row
      style="width:100%"
      type="flex"
    >
      <a-col flex="150px">
        <span style="fontSize:20px;color:#027bd9">配送商品明细</span>
      </a-col>
      <a-col
        flex="auto"
        class="batchInput"
      >
        <search-layout
          :formInfos="i_formInfos"
          :formDatas="i_formDatas"
          message=""
          @onFind="onFill"
        ></search-layout>
      </a-col>
    </a-row>
    <a-list-table
      tableId="goodsTable1"
      :columns="columns"
      :tableData="listdata"
      :haveChild="true"
      :pagination="pagination"
      :isSelecttion="false"
      :isInnerSelecttion="true"
      :isExpandAllRows="true"
      @onInnerSelect="onInnerSelect"
      :loading="loading"
      :scroll="{y:null}"
      @onTableChange="handleTableChange"
      @onselectChange="onselectChange"
      @onAction="onAction"
      @expand="onExpand"
      :links="links"
      :autoComputed="autoComputed"
      @onTouchlinkCell="onTouchlinkCell"
      :innerTable="innerTable"
      @onInnerAction="onInnerAction"
      @onInnerChangeInput="onInnerChangeInput"
      @clearSelect="clearSelect"
    >
    </a-list-table>
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import aListTable from '@/views/app/biz/common/aListTable'
import {
  getMergeByConditions,
  checkDetailNum
} from './saleDelivery'
import {
  columns, innerTable
} from './mergeStepConfig'


let links = ['saleOrderNo',]
let autoComputed = ['execNum', 'totalPrice']
let inputNameObj = [
  { name: 'commonName', type: 'text', placeholder: '通用名' },
]
export default {
  components: {
    searchLayout,
    batchOperatBtn,
    aListTable
  },
  props: {
    detailData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      //批量填入表单
      i_formInfos: [
        { label: '', name: 'batchCode', type: 'input', isDisabled: true, placeholder: '批号' },
        // {label: '',name:'execNum',type:'number',isDisabled:true,placeholder:'数量'},
        { label: '', name: 'productDate', type: 'productDate', isDisabled: true, placeholder: '生产日期' },
        { label: '', name: 'expiryDate', type: 'expiryDate', isDisabled: true, placeholder: '有效期' },
        { label: ['批量填入',], type: 'botton' }
      ],
      i_formDatas: {
        // execNum: null,
        batchCode: null,
        productDate: null,
        expiryDate: null
      },
      columns: columns,
      listdata: [],
      links: links,
      autoComputed: autoComputed,
      inputNameObj: inputNameObj,
      loading: false,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 100000, //每页显示条数 pageSize
        total: 1,
        // showQuickJumper: true,
        // showSizeChanger: true,
        // pageSizeOptions: ['2', '10', '50', '100'],
      },
      pData: {}, // 条件查询参数
      isJump: false,
      optText: '确认订单',
      selectedRowKeys: [],
      selectedRows: [],
      listdata_sel: [],
      notAudit: false,
      innerTable: innerTable
    }
  },
  watch: {
    listdata: {
      handler: function (val, oldVal) {
      },
      deep: true,
      immediate: true
    },
    detailData: {
      handler: function (val, oldVal) {
        this.listdata = [...val]

      },
      deep: true,
      immediate: true
    },
  },
  computed: {},
  created () {
    this.listdata = [...this.detailData]
  },
  updated () {
  },

  mounted () {

  },
  methods: {
    // 操作按钮
    onAction (text, record, index) {
      if (text == '删除') {
        let that = this
        this.$confirm({
          title: '是否确认删除？',
          content: '删除后不可恢复！',
          onOk () {
            console.log(that.listdata);
            that.listdata.splice(index, 1)
            that.clearSelect(record)
          },
          onCancel () { },
        });
      }
    },
    onInnerAction (text, record, index) {
      if (text == '删除') {
        this.delInnerItem(text, record, index)
      } else if (text == '添加') {
        this.addInnerItem(text, record, index)
      } else if (text == '移除') {
        this.removeInnerItem(text, record, index)
      }
    },
    addInnerItem (text, record, index) {
      console.log(record);
      let parentItem = this.listdata.find(item => { return item.saleGoodsPid == record.saleGoodsPid })
      let newRecord = JSON.parse(JSON.stringify(record))
      newRecord.action = ['移除']
      newRecord.execNum = null
      newRecord.batchCode = null
      newRecord.productDate = null
      newRecord.expiryDate = null
      newRecord.key = new Date().getTime()
      let optInd = parentItem.child.findIndex(item => { return item.key == record.key })
      parentItem.child.splice(optInd + 1, 0, newRecord)
      this.clearSelect(record)
    },
    removeInnerItem (text, record, index) {
      console.log(record);
      let parentItem = this.listdata.find(item => {
        return item.saleGoodsPid == record.saleGoodsPid
      })
      parentItem.child.splice(index, 1)
      this.clearSelect(record)
    },
    delInnerItem (text, record, index) {
      let that = this
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk () {
          console.log(record);
          let parentItem = that.listdata.find(item => {
            return item.saleGoodsPid == record.saleGoodsPid
          })
          parentItem.child.splice(index, 1)
          that.clearSelect(record)
        },
        onCancel () { },
      });
    },
    // 触发改变页码,筛选,排序时的回调
    handleTableChange (pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    //点击展开表格
    onExpand (expanded, record) {
      console.log(expanded, record);
    },
    onInnerChangeInput (target, value, key, column, index) {

    },
    // 查询按钮
    onFill () {
      for (let item of this.listdata) {
        if (item.selectedRowKeys.length) {
          for (let itemc of item.child) {
            let isInSelArr = item.selectedRowKeys.find(ite => {
              return ite == itemc.key
            })
            console.log(isInSelArr);
            if (isInSelArr) {
              // itemc.execNum=this.i_formDatas.execNum
              itemc.batchCode = this.i_formDatas.batchCode
              itemc.productDate = this.i_formDatas.productDate
              itemc.expiryDate = this.i_formDatas.expiryDate
            }
          }
        }

        item.selectedRowKeys = []
      }
      this.listdata = [...this.listdata]
      this.setDisable()
      // this.initSelect(null)
    },

    onTouchlinkCell (text, record, index, link) {
      console.log(record);
      if (link == 'saleOrderNo') {
        this.$refs.viewSaleOrderModal.showModal(record.pid, record)
      }
    },
    // 多选批量操作
    onselectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (const item of this.selectedRows) {
        if (item.action[0] != '确认') {
          this.notAudit = true
          return
        } else {
          this.notAudit = false
        }
      }
    },
    // 子表格多选批量操作
    onInnerSelect (selectedRowKeys, selectedRows, record) {
      // console.log("*************************************");
      // console.log(selectedRowKeys, selectedRows,record);

      let parScdind = this.listdata.findIndex(item => {
        return item.pid == record.pid
      })
      this.listdata[parScdind].selectedRowKeys = selectedRowKeys
      this.setDisable()
    },
    clearSelect (record) {
      // console.log(record);
      // console.log("____________________________________");
      this.initSelect(record)
    },
    initSelect (record) {//purProdPid
      for (let item of this.listdata) {
        console.log(record);
        if (record.purProdPid == item.purProdPid) {
          item.selectedRowKeys = []
        }
      }
      this.listdata = [...this.listdata]
      this.setDisable()
    },
    setDisable () {
      //循环数组，如果有选择，则批量栏可填
      let haveSel = false
      for (let item of this.listdata) {
        if (item.selectedRowKeys.length) {
          haveSel = true
        }
      }
      for (let el of this.i_formInfos) {
        if (haveSel) {
          el.isDisabled = false
        } else {
          el.isDisabled = true
        }
      }
      this.i_formInfos = [...this.i_formInfos]
    },
    onBatchAudit () {
      if (this.selectedRows.length) {
        if (this.notAudit) {
          this.$message.warning({ content: '已选项中含有已确认的记录，请选择未确认的记录', duration: 3 })
        } else {
          this.showConfirm(this.selectedRows)
        }
      } else {
        this.$message.warning({ content: '未选择要审核的记录', duration: 3 })
      }
    },
    onNext () {
      console.log(this.listdata);
      let next = true
      if (this.listdata.length) {
        outloop:
        for (const item1 of this.listdata) {
          for (const item2 of item1.child) {
            if (!item2.batchCode) {
              this.$message.warning({ content: '商品批号不能为空', duration: 3 })
              next = false
              break outloop;
            }
            if (!item2.execNum) {
              this.$message.warning({ content: '配送数量必须大于0', duration: 3 })
              next = false
              break outloop;
            }
            if (!item2.productDate) {
              this.$message.warning({ content: '生产日期不能为空', duration: 3 })
              next = false
              break outloop;
            }
            if (!item2.expiryDate) {
              this.$message.warning({ content: '有效期不能为空', duration: 3 })
              next = false
              break outloop;
            }
          }

        }
        if (next) {
          this.checkDetailNum(this.listdata)
        }
      } else {
        this.$message.warning({ content: '未添加商品信息', duration: 3 })
      }
    },
    async checkDetailNum (sbData) {
      // this.$message.loading({content:'数据校验中'})
      let sData = {
        deliveryOrderDetails: sbData
      }
      let res = await checkDetailNum(sData)
      console.log(res);
      if (res && res.code == "C1") {
        if (res.data > 0) {
          this.$message.warning({ content: '明细数量有误' })
        } else {
          this.$emit('onNextStep', this.listdata)
        }

      } else {
        this.$message.error({ content: '请求出错' + res.message })
      }
    }
  },
}
</script>

<style>
.batchInput {
  display: flex;
  justify-content: right;
  align-items: center;
}
</style>